package cn.xspace.module.other.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.xspace.android.imcommon.entity.ChatMsg;
import com.xspace.android.imcommon.fileupload.IuploadListener;
import com.xspace.android.imcommon.fileupload.UploadMg;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.CommonItemBean;
import com.xspace.android.xafcommon.been.MediaBean;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.AppManager;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.CloseUtils;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.StringUtils;
import com.xspace.android.xafcommon.view.dialog.BottomSelectDialog;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.ConfirmDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.ui.activity.LoginAct;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.BuildCache;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpUtils;
import cn.xspace.library.util.Tools;
import cn.xspace.module.other.R;
import cn.xspace.module.other.bean.UserInfoBeanNew;
import cn.xspace.module.other.http.impl.ModifyUserInfoImpl;
import cn.xspace.module.other.http.impl.QueryUserInfoImpl;
import cn.xspace.module.other.util.RProxy;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UserInfoAct extends BaseActivity /*implements View.OnClickListener*/ {

    public static final String TAG = UserInfoAct.class.getSimpleName();

    static final int ITEM_PICTURE = 1;
    static final int ITEM_TAKE_PICTURE = 2;
    static final int ITEM_LOCATION = 3;
    static final int ITEM_FILE = 4;
    protected File cameraFile;

    public static final int SEXSET_FORREULR = 101;
    public static final int SIGNATURE_FORREULR = 102;
    public static final int PLACESET_FORREULR = 103;
    private static final int TAKE_PIC = 0;
    private static final int CHOOSE_PIC = 1;
    private static final int WOMEN = 2;
    private static final int MAN = 3;
    public static String ACTION_REFRESH_INFO = "justRefreshingInfo";
    private QueryUserInfoImpl queryUserInfo;
    private ModifyUserInfoImpl modifyUserInfo;
    private PopupWindow windowTitle = null;
    private String place_id = "";
    private RelativeLayout layout_username;
    private long exitTime = 0;

    private Context mContext;
    private String userId;
    private TextView userName;
    private TextView userAccount;
    private TextView userPlace;
    private TextView userSex;
    private TextView userSignature;
    private ImageView userIcon;
    private TitleBar titleBar;
    private UserInfoBeanNew userInfoBeanNew;
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//        queryUserInfo = new QueryUserInfoImpl(this);
//        modifyUserInfo = new ModifyUserInfoImpl(this);
////        changeView();
//        super.setPhotoZoom(true);
//    }

    @Override
    protected void initView() {
        setContentView(R.layout.userinfoact);
    }

    @Override
    protected void initData() {
        mContext = this;
        userId = MyInfoUtil.getMyUserid(mContext);
        EventBus.getDefault().register(mContext);
        AppUtils.createDir(Constants.IMAGE_HEAD);
        requestNetData();
    }

    @Override
    protected void initEvent() {
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initFindViewById() {
        userIcon = (ImageView) findViewById(R.id.userinfoact_header_imgView); //头像
        userName = (TextView) findViewById(R.id.userinfoact_name_show_txtView);  //用户名
        userAccount = (TextView) findViewById(R.id.userinfoact_account_show_txtView);//帐号
        userPlace = (TextView) findViewById(R.id.userinfoact_place_show_txtView);//地址
        userSex = (TextView) findViewById(R.id.userinfoact_sex_show_txtView);//性别
        userSignature = (TextView) findViewById(R.id.userinfoact_signature_show_txtView); //个签
        titleBar = (TitleBar) findViewById(R.id.setting_title_bar);
    }

    /**
     * xml中的点击事件
     *
     * @param view
     */
    public void switchStatus(View view) {
        showExitDialog();
    }

    // 跳转入地区设置界面
    public void placeSet(View view) {
        Intent intent_address = new Intent(UserInfoAct.this, PlaceSetAct.class);
        intent_address.putExtra("ishowcheck", true);
        intent_address.putExtra("isFromUserInfo", true);
        intent_address.putExtra("areaCodeLength", 30);
        /**
         * @author wangtao
         * eventbus
         */
//        startActivityForResult(intent_address, PLACESET_FORREULR);
        startActivity(intent_address);
    }

    // 跳转入签名设置界面
    public void signature(View view) {
        Intent intent_signature = new Intent(UserInfoAct.this, SignatureAct.class);
        intent_signature.putExtra("SignatureAct", userSignature.getText().toString().trim());
//        startActivityForResult(intent_signature, SIGNATURE_FORREULR);
        startActivity(intent_signature);
    }

    // 跳转入性别设置界面
    public void sexSet(View view) {
//        Intent intent_sex = new Intent(UserInfoAct.this, SexSetAct.class);
//        intent_sex.putExtra("SexSetActivity",
//                ((TextView) findViewById(RProxy.userinfoact_sex_show_txtView)).getText().toString());
//        startActivityForResult(intent_sex, SEXSET_FORREULR);
//        startActivity(intent_sex);
        showSexDialog();
    }


    // 头像设置界面
    public void headSet(View view) {
//        showOutMenu();
        showPhotoDialog();
    }

    /**
     * 设置性别的对话框
     */
    private void showSexDialog() {
        List<CommonItemBean> list = new ArrayList<>();
        list.add(new CommonItemBean(getString(R.string.sex_man), 0));
        list.add(new CommonItemBean(getString(R.string.sex_women), 1));
//        final List<String> stringList = new ArrayList<>();
//        stringList.add(TAKE_PIC, ResourceUtils.getString(R.string.sex_man));
//        stringList.add(CHOOSE_PIC, ResourceUtils.getString(R.string.sex_women));
        BottomSelectDialog dialog = new BottomSelectDialog.Builder(mContext).build();
        dialog.setSingleChoiceItems(list, new BottomSelectDialog.ISelectItemListener() {
            @Override
            public void clickListener(View view, CommonItemBean bean, int position) {
                switch (bean.tag) {
                    case 0: //男
                        userSex.setText(ResourceUtils
                                .getString(R.string.sex_man));
//                        map.put("type", "SexSetAct");
//                        map.put("UserInfoAct", "男");
//                        map.put("sure_ok", "true");
//                        EventBus.getDefault().post(map);

                        uploadData("user_sex", "男");
                        break;
                    case 1: //女
                        userSex.setText(ResourceUtils
                                .getString(R.string.sex_women));
//                        map.put("type", "SexSetAct");
//                        map.put("UserInfoAct", "女");
//                        map.put("sure_ok", "true");
//                        EventBus.getDefault().post(map);
                        uploadData("user_sex", "女");
                        break;
                }
            }
        }).show();
    }

    /**
     * 更新用户数据
     *
     * @param parame 参数
     * @param data   数据
     */
    private void uploadData(final String parame, final String data) {
        final Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        map.put(parame, data);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.UPDATE_USER_INFO, map);
                if (OkHttpUtils.isSuccess(bean)) {
                    LogUtil.e("UserInfoAct     =======     返回结果成功");
                    subscriber.onNext(bean);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                LogUtil.e("UserInfoAct     =======     失败");
            }

            @Override
            public void onNext(Object result) {
                if (result != null) {
                    LogUtil.e("UserInfoAct     =======     返回结果 " + ((BaseReturnBean) result).code);
                    if (parame.equals("user_logo")) {
                        //保存用户头像信息
                        BuildCache.getAppConfigBean(mContext).userInfoBean.user_logo = data;
                        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_LOGO, data);
                        Picasso.with(mContext).load(data).into(userIcon);
                        Map<String, Object> map = new HashMap<>();
                        map.put(EventBusConstant.TYPE, EventBusConstant.LOGO_UPLOAD_FINISHED);
                        map.put(EventBusConstant.ACTION_KEY, data);
                        EventBus.getDefault().post(map);
                    }
                }
            }
        });

    }

    /**
     * 设置头像的对话框
     */
    private void showPhotoDialog() {
        List<CommonItemBean> list = new ArrayList<>();
        list.add(new CommonItemBean(getString(R.string.userinfoact_choose_a_pic), TAKE_PIC));
        list.add(new CommonItemBean(getString(R.string.userinfoact_take_a_pic), CHOOSE_PIC));
//        final List<String> stringList = new ArrayList<>();
//        stringList.add(TAKE_PIC, ResourceUtils.getString(R.string.userinfoact_choose_a_pic));
//        stringList.add(CHOOSE_PIC, ResourceUtils.getString(R.string.userinfoact_take_a_pic));
        BottomSelectDialog dialog = new BottomSelectDialog.Builder(mContext).build();
        dialog.setSingleChoiceItems(list, new BottomSelectDialog.ISelectItemListener() {
            @Override
            public void clickListener(View view, CommonItemBean bean, int position) {
                switch (bean.tag) {
                    case TAKE_PIC: //拍照
                        String headName = ((TextView) findViewById(RProxy.userinfoact_account_show_txtView)).getText
                                ().toString();
                        if (StringUtils.isEmpty(headName)) {
                            headName = System.currentTimeMillis() + ".jpg";
                        }
                        selectPicFromLocal();
//                        startCmaera(Constants.IMAGE_HEAD + headName);
                        break;
                    case CHOOSE_PIC: //本地选择照片
                        selectPicFromCamera();
                        String headPictureName = System.currentTimeMillis() + ".jpg";
//                        choiceCmaera(Constants.IMAGE_HEAD + headPictureName);
                        break;
                }
            }
        }).show();
    }


    /**
     * 从相册选择图片
     */
    private void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, ITEM_PICTURE);
    }

    /**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!ResourceUtils.isSdcardExist()) {
            Toast.makeText(mContext, R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        String name = System.currentTimeMillis() + ".jpg";
        LogUtil.d(TAG, "camera name " + name);
        cameraFile = new File(AppConstant.IMAGE_ADDRESS, name);
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri
                .fromFile(cameraFile)), ITEM_TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d(TAG, "wubaojie>>>onActivityResult: resultCode:" + requestCode);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == ITEM_TAKE_PICTURE) { // 拍照
                if (cameraFile != null && cameraFile.exists()) {
                    LogUtil.d(TAG, "wubaojie>>>onActivityResult: Path:" + cameraFile.getAbsolutePath());
                    LogUtil.d(TAG, "wubaojie>>>onActivityResult: Name:" + cameraFile.getName());

                    MediaBean mediaBean = new MediaBean();
                    mediaBean.insert_time = String.valueOf(System.currentTimeMillis());
                    mediaBean.file_name = cameraFile.getName();
                    mediaBean.file_type = "0";
                    mediaBean.file_state = "0";
                    mediaBean.path_type = "0";
                    mediaBean.content = cameraFile.getAbsolutePath();
                    mediaBean.pic_shoot_time = System.currentTimeMillis() + "";
                    updatePic(mediaBean);
                }
            } else if (requestCode == ITEM_PICTURE) { //相册选择图片
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
            }
        }
    }

    protected ArrayList<ChatMsg> uploadList = new ArrayList<>();

    private void updatePic(MediaBean mediaBean) {
        if ("0".equals(mediaBean.file_state)) {
            ChatMsg info = new ChatMsg();
            info.mFileType = mediaBean.file_type;
            info.fileType = mediaBean.content_type;//后缀名
            info.mSendTime = DateUtils.getNowDateTime();
            info.msgId = System.currentTimeMillis();
            info.fromUser = MyInfoUtil.getMyUserid(mContext);
            info.mUUID = MyInfoUtil.getMyUserid(mContext);
            info.platForm = "worklog";
            info.fileName = mediaBean.file_name;
            info.imgPath = mediaBean.content;
            info.picShootTime = mediaBean.pic_shoot_time;

            if (TextUtils.isEmpty(info.fileType) && !TextUtils.isEmpty(info.fileName)) {
                info.fileType = info.fileName.substring(info.fileName.indexOf(".") + 1, info.fileName
                        .length());
            }
            info.uploadUrl = Constants.upLoadFileCommon;
            uploadList.add(info);
            UploadMg.getInstance().uploadFile(uploadList, iuploadListener);
        }
    }

    IuploadListener iuploadListener = new IuploadListener() {
        @Override
        public void onUploadBefore(ChatMsg uploads) {

        }

        @Override
        public void onUploading(int position, long uploaded, long total, float progress, float speed, ChatMsg
                uploads, int current) {
            showWaitDialog("正在上传头像");
        }

        @Override
        public void onUploadError(int position, long uploaded, float progress, ChatMsg uploads, int current) {
//            isHaveFailed = true;
        }

        @Override
        public void onUploadAllFinished(int position, ChatMsg uploads, boolean checkFlag) {
//            uploadFileFinish(uploads);
            hideWaitDialog();
            String url = uploads.mContent;
            LogUtil.e("UserInfoAct    ====       返回图片地址  " + url);
            uploadData("user_logo", url);
//            Picasso.with(mContext).load(url).into(userIcon);
//            Map<String, Object> map = new HashMap<>();
//            map.put(EventBusConstant.TYPE, EventBusConstant.LOGO_UPLOAD_FINISHED);
//            map.put(EventBusConstant.ACTION_KEY, url);
//            EventBus.getDefault().post(map);
//            //保存用户头像信息
//            BuildCache.getAppConfigBean(mContext).userInfoBean.logo = url;
//            PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_LOGO, url);
        }

        @Override
        public void onCancelUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onPauseUpload(int position, ChatMsg uploads, int current) {

        }

        @Override
        public void onResumeUpload(int position, ChatMsg uploads, int current) {

        }
    };


    /**
     * 相册中选择图片
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
                CloseUtils.closeIO(cursor);
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(mContext, R.string.file_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(mContext, R.string.file_is_not_greater_than_10_m, Toast
                    .LENGTH_SHORT).show();
            return;
        }
        MediaBean mediaBean = new MediaBean();
        mediaBean.insert_time = String.valueOf(System.currentTimeMillis());
        mediaBean.file_name = file.getName();
        mediaBean.file_type = "0";
        mediaBean.file_state = "0";
        mediaBean.path_type = "0";
        mediaBean.content = file.getAbsolutePath();
        updatePic(mediaBean);
    }

    // 跳转入设置密码界面
    public void gotoReSetPwdAct(View view) {
        Intent i = new Intent();
        i.putExtra("user_mobile", userInfoBeanNew.user_mobile);
        i.setClass(this, ReSetPwdAct.class);
        startActivity(i);
    }

    // 跳转入登陆界面
    private void gotoLoginAct() {
        //		Tools.exitApp(UserInfoAct.this);
        Intent i = new Intent();
        i.setClass(this, LoginAct.class);
        startActivity(i);
    }

    /**
     * 弹出退出对话框
     */
    private void showExitDialog() {
        new ConfirmDialog.Builder(mContext).setTitleMsg(getString(R.string.userinfoact_switch_btn_exitapp_txt))
                .setContentMsg(getString(R.string.msgexit))
                .setLeftText(getString(R.string.cancel))
                .setRightText(getString(R.string.button_ok))
                .setMaxLine(2)
                .setRightListener(new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
//                        Toast.makeText(mContext, "确认退出", Toast.LENGTH_SHORT).show();
//                        showWaitDialog();
//                        Intent mIntent = new Intent(mContext, WnxService.class);
//                        mIntent.putExtra(ModuleConfig.OPERATION, WnxService.XMPP_LOGIN_OUT);
//                        startService(mIntent);
                        Tools.exitApp(UserInfoAct.this);
                        // 停止XMPP推送服务,内部包含断线重连等设置
                        PreferencesUtils.SaveBooleanData("LogoutNormal", true);
                        BldNavigation.HxXmppLoginout(mContext);
                        HashMap<String, Object> inParam = new HashMap<>();
                        inParam.put(EventBusConstant.TYPE, TAG);
                        inParam.put(EventBusConstant.ACTION_KEY, EventBusConstant.LONGIN_OUT);
                        EventBus.getDefault().post(inParam);
                        AppManager.getAppManager().finishAllActivity();
                        Intent in = new Intent(UserInfoAct.this, LoginAct.class);
                        startActivity(in);
                    }
                })
                .setListener().show();
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        super.onEventMainThread(inParam);
        String type = inParam.get(EventBusConstant.TYPE).toString();
        if (PlaceSetAct.TAG.equals(type)) { //地区
//            commit("areainfo", address, RProxy.userinfoact_place_show_txtView);
//            modifyUserInfo(place_id, TYPE_PLACE);
            place_id = (String) inParam.get("PlaceCode");
            String address = (String) inParam.get("Place");
            userPlace.setText(address);
            uploadData("user_areacode", place_id);
        } else if ("SignatureAct".equals(type)) {  // 签名
            String desc = (String) inParam.get("SignatureAct");
//            commit("summary", value, RProxy.userinfoact_signature_show_txtView);
//            modifyUserInfo(value, TYPE_DESC);
//            if (desc.length() > 10) {
//                desc = desc.substring(0, 10);
//            }
            userSignature.setText(desc);
        }
//        } else if (map.get("type").equals("onUploadAllFinished")) { //头像
//            String url = (String) map.get("newPicUrl");
//            Picasso.with(mContext).load(url).into(userIcon);
//        }
    }

    private void requestNetData() {
        showWaitDialog();
        LogUtil.e("UserInfoAct     =======     开始请求数据 " + userId);
        final Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", userId);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.QUERY_USER_INFO, requestMap);
                if (OkHttpUtils.isSuccess(bean)) {
                    UserInfoBeanNew userInfoBeanNew = JSONUtil.parseJsonToBean(bean.data, UserInfoBeanNew.class);
                    subscriber.onNext(userInfoBeanNew);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                hideWaitDialog();
                LogUtil.e("UserInfoAct     =======     请求数据失败 " + userId);
                throwable.printStackTrace();
            }

            @Override
            public void onNext(Object result) {
                hideWaitDialog();
                userInfoBeanNew = (UserInfoBeanNew) result;
                LogUtil.e("UserInfoAct     =======     请求数据成功 " + userInfoBeanNew.user_name);
//                        userIcon
                if (userInfoBeanNew != null) {
                    LogUtil.e("UserInfoAct     =======     请求图片地址为 " + userInfoBeanNew.user_logo);
                    Picasso.with(mContext).load(userInfoBeanNew.user_logo).into(userIcon);
                    userName.setText(userInfoBeanNew.user_name);
                    userAccount.setText(userInfoBeanNew.user_mobile);
                    userPlace.setText(userInfoBeanNew.user_address);
                    String desc = userInfoBeanNew.user_desc;
//                    if (!"".equals(desc))
//                        if (desc.length() > 10) {
//                            desc = desc.substring(0, 10);
//                        }
                    userSignature.setText(desc);
                    userSex.setText(userInfoBeanNew.user_sex);
                }
            }
        });
    }
}
